package com.mflex.flexwi;

import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.collection.SimpleArrayMap;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import com.dou361.dialogui.DialogUIUtils;
import com.king.zxing.CameraScan;
import com.mflex.flexwi.adapter.WIAdapter;
import com.mflex.flexwi.bean.WIItem;
import com.mflex.flexwi.fragment.WIDataFragment;
import com.mflex.flexwi.util.CommonUtil;
import com.mflex.flexwi.util.SoapObjectUtil;
import com.mflex.flexwi.util.WebServiceUtil;
import com.rosefinches.smiledialog.SmileDialog;
import com.rosefinches.smiledialog.SmileDialogBuilder;
import com.rosefinches.smiledialog.enums.SmileDialogType;
import com.rosefinches.smiledialog.interfac.OnConformClickListener;

import org.apache.commons.lang3.StringUtils;
import org.ksoap2.serialization.SoapObject;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

public class MainActivity extends BaseActivity {
    private static String userNmae;
    private static String userPassword;
    private static String webServiceUrl;
    private static String pdfUrlBase;
    private static String fileType;

    private EditText txtsLot;
    private EditText txtsMachine;
    private EditText txtsFileNo;
    private EditText txtsProduct;
    private EditText txtsMachineGroup;
    private EditText txtsFileName;
    private Spinner txtsFileType;
    private Button btnClear;
    private Button btnSerach;
    private ListView lvWI;

    private ImageButton imageButtonFileNo;
    private ImageButton imageButtonFileName;
    private ImageButton imageButtonLot;
    private ImageButton imageButtonMachine;
    private ImageButton imageButtonMachineGroup;
    private ImageButton imageButtonProduct;

    public final int REQUEST_CODE_FILE_NO = 1;
    public final int REQUEST_CODE_FILE_NAME = 2;
    public final int REQUEST_CODE_LOT = 3;
    public final int REQUEST_CODE_MACHINE = 4;
    public final int REQUEST_CODE_MACHINE_GROUP = 5;
    public final int REQUEST_CODE_PRODUCT = 6;

    private ArrayAdapter<CharSequence> job_adapter;


    private List<WIItem> wiList;
    private List<String> mItems;

    private WIDataFragment mWIDataFragment;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        DialogUIUtils.init(this);
        if(CommonUtil.isTabletDevice(this)){
            int orientation=getResources().getConfiguration().orientation;
            if(orientation== Configuration.ORIENTATION_LANDSCAPE){
                setContentView(R.layout.activity_main_h);
            }else if(orientation==Configuration.ORIENTATION_PORTRAIT){
                setContentView(R.layout.activity_main_v);
            }
            imageButtonFileNo = (ImageButton) findViewById(R.id.imageButtonFileNo);
            imageButtonFileName = (ImageButton) findViewById(R.id.imageButtonFileName);
            imageButtonLot = (ImageButton) findViewById(R.id.imageButtonLot);
            imageButtonMachine = (ImageButton) findViewById(R.id.imageButtonMachine);
            imageButtonMachineGroup = (ImageButton) findViewById(R.id.imageButtonMachineGroup);
            imageButtonProduct = (ImageButton) findViewById(R.id.imageButtonProduct);
            imageButtonFileNo.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent=new Intent(MainActivity.this,CustomActivity.class);
                    startActivityForResult(intent,REQUEST_CODE_FILE_NO);
                }
            });
            imageButtonFileName.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent=new Intent(MainActivity.this,CustomActivity.class);
                    startActivityForResult(intent,REQUEST_CODE_FILE_NAME);
                }
            });
            imageButtonLot.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent=new Intent(MainActivity.this,CustomActivity.class);
                    startActivityForResult(intent,REQUEST_CODE_LOT);
                }
            });
            imageButtonMachine.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent=new Intent(MainActivity.this,CustomActivity.class);
                    startActivityForResult(intent,REQUEST_CODE_MACHINE);
                }
            });
            imageButtonMachineGroup.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent=new Intent(MainActivity.this,CustomActivity.class);
                    startActivityForResult(intent,REQUEST_CODE_MACHINE_GROUP);
                }
            });
            imageButtonProduct.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent=new Intent(MainActivity.this,CustomActivity.class);
                    startActivityForResult(intent,REQUEST_CODE_PRODUCT);
                }
            });
        }else{
            setContentView(R.layout.activity_main);
        }

        Intent intent = getIntent();
        userNmae = intent.getStringExtra("userName");
        userPassword = intent.getStringExtra("userPassword");
        webServiceUrl = intent.getStringExtra("webServiceUrl");
        pdfUrlBase = intent.getStringExtra("pdfUrl");

        txtsLot = (EditText) findViewById(R.id.txtsLot);
        txtsMachine = (EditText) findViewById(R.id.txtsMachine);
        txtsFileNo = (EditText) findViewById(R.id.txtsFileNo);
        txtsProduct = (EditText) findViewById(R.id.txtsProduct);
        txtsMachineGroup = (EditText) findViewById(R.id.txtsMachineGroup);
        txtsFileName = (EditText) findViewById(R.id.txtsFileName);
        txtsFileType = (Spinner) findViewById(R.id.txtsFileType);
        btnClear = (Button) findViewById(R.id.btnClear);
        btnSerach = (Button) findViewById(R.id.btnSerach);
        lvWI = (ListView) findViewById(R.id.lvWI);

        FragmentManager fragmentManager = getSupportFragmentManager();
        mWIDataFragment = (WIDataFragment) fragmentManager.findFragmentByTag("data");
        if (mWIDataFragment == null) {
            mWIDataFragment = new WIDataFragment();
            FragmentTransaction transaction = fragmentManager.beginTransaction();
            transaction.add(mWIDataFragment, "data");
            transaction.commit();
        }
        wiList = collectLoadedData();
        if (wiList == null) {

        }else{
            WIAdapter wiAdapter = new WIAdapter(MainActivity.this, wiList);
            lvWI.setAdapter(wiAdapter);
        }

        txtsFileType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
//                Toast.makeText(MainActivity.this, "你点击的是:"+mItems.get(position),Toast.LENGTH_LONG).show();
                fileType = mItems.get(position);
                TextView tv = (TextView) view;
                tv.setTextColor(getResources().getColor(com.dou361.dialogui.R.color.text_gray));    //设置颜色

                tv.setTextSize(14.0f);    //设置大小

//                tv.setGravity(android.view.Gravity.CENTER_HORIZONTAL);   //设置居中

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        requestFileType();


        btnSerach.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                request();
            }
        });

        btnClear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                txtsFileName.setText(StringUtils.EMPTY);
                txtsFileNo.setText(StringUtils.EMPTY);
                txtsLot.setText(StringUtils.EMPTY);
                txtsMachineGroup.setText(StringUtils.EMPTY);
                txtsMachine.setText(StringUtils.EMPTY);
//                txtSpec.setText(StringUtils.EMPTY);
//                txtWorkCenter.setText(StringUtils.EMPTY);
                txtsProduct.setText(StringUtils.EMPTY);
                txtsFileType.setSelection(0);
                fileType = "ALL";
            }
        });

        lvWI.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent(MainActivity.this, PdfDetailActive.class);
                intent.putExtra("pdfUrlBase", pdfUrlBase);
                intent.putExtra("pdfUrl", wiList.get(position).getIdentifier());
                intent.putExtra("pdfTitle", wiList.get(position).getProduct());
                intent.putExtra("webServiceUrl", webServiceUrl);
                intent.putExtra("docName", wiList.get(position).getFileName());
                intent.putExtra("docNumber", wiList.get(position).getFileNo());
                intent.putExtra("docVersion", wiList.get(position).getFileVersion());
                startActivity(intent);
            }
        });


    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_UP) {
            SmileDialog dialog = new SmileDialogBuilder(MainActivity.this, SmileDialogType.WARNING)
                    .setTitleText("System prompt")
                    .setContentText("Are you sure you want to return?")
                    .setCancelButton("Cancel")
                    .setCancelBgColor(Color.LTGRAY)
                    .setConformBgColor(Color.LTGRAY)
                    .setOnConformClickListener(new OnConformClickListener() {
                        @Override
                        public void onConformClicked() {
                            MainActivity.this.finish();
                        }
                    })
                    .build();
            dialog.show();
            return true;
        }
        //继续执行父类其他点击事件
        return super.onKeyUp(keyCode, event);
    }

    private void request() {
        final Dialog bean = DialogUIUtils.showLoading(this, "Querying, please wait a moment...", false, false, false, false).show();
        SimpleArrayMap<String, Object> map = new SimpleArrayMap<>();
//        map.put("Result", new Object());
        map.put("Product", txtsProduct.getText().toString());
        map.put("Machine", txtsMachine.getText().toString());
        map.put("Lot", txtsLot.getText().toString());
        map.put("MachineGroup", txtsMachineGroup.getText().toString());
        map.put("FileNo", txtsFileNo.getText().toString());
        map.put("FileName", txtsFileName.getText().toString());
        map.put("FileType", StringUtils.equals(fileType, "ALL") ? StringUtils.EMPTY : fileType);
        WebServiceUtil.call(webServiceUrl, "GetWIDetail2", map, new WebServiceUtil.ResponseCallBack() {
            @Override
            public void onSuccess(Object result) {
                SoapObject soapresult = (SoapObject) result;
                wiList = new ArrayList<>();
                int count = soapresult.getPropertyCount();
                for (int i = 0; i < count; i++) {
                    SoapObject soapresult1 = (SoapObject) soapresult.getProperty(i);
                    WIItem wiItem = new WIItem();
                    try {
                        wiItem = SoapObjectUtil.soapToPojo(WIItem.class, soapresult1);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    } catch (InvocationTargetException e) {
                        e.printStackTrace();
                    } catch (NoSuchMethodException e) {
                        e.printStackTrace();
                    } catch (InstantiationException e) {
                        e.printStackTrace();
                    }
                    wiList.add(wiItem);
                }
                WIAdapter wiAdapter = new WIAdapter(MainActivity.this, wiList);
                lvWI.setAdapter(wiAdapter);
                DialogUIUtils.dismiss(bean);
            }

            @Override
            public void onError(String e) {

                DialogUIUtils.dismiss(bean);
                SmileDialog dialog = new SmileDialogBuilder(MainActivity.this, SmileDialogType.ERROR)
                        .setContentText(e)
                        .setTitleText("Error message")
                        .build();
                dialog.show();
            }
        });
    }

    private void requestFileType() {

        SimpleArrayMap<String, Object> map = new SimpleArrayMap<>();
//        map.put("Product", txtsProduct.getText().toString());
        WebServiceUtil.call(webServiceUrl, "GetFileType", map, new WebServiceUtil.ResponseCallBack() {
            @Override
            public void onSuccess(Object result) {
                try {
                    SoapObject  soapresult = (SoapObject) result;
                    mItems = new ArrayList<>();
                    mItems.add("ALL");
                    int count = soapresult.getPropertyCount();
                    for (int i = 0; i < count; i++) {
                        mItems.add(soapresult.getProperty(i).toString());
                    }
                    ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, mItems);
                    txtsFileType.setAdapter(adapter);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onError(String e) {
                SmileDialog dialog = new SmileDialogBuilder(MainActivity.this, SmileDialogType.ERROR)
                        .setContentText(e)
                        .setTitleText("Error message")
                        .build();
                dialog.show();
            }
        });
    }

    @Override
    protected void onDestroy() {
        mWIDataFragment.setWiList(wiList);
        super.onDestroy();
    }

    private List<WIItem> collectLoadedData() {
        return mWIDataFragment.getWiList();
    }

    // 扫码界面回调方法
    @Override
    protected  void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode,resultCode,data);
        switch(requestCode){
            case REQUEST_CODE_FILE_NO:
                if(!StringUtils.isEmpty(CameraScan.parseScanResult(data))){
                    txtsFileNo.setText(CameraScan.parseScanResult(data));
                }
                break;
            case REQUEST_CODE_FILE_NAME:
                if(!StringUtils.isEmpty(CameraScan.parseScanResult(data))){
                    txtsFileName.setText(CameraScan.parseScanResult(data));
                }
                break;
            case REQUEST_CODE_LOT:
                if(!StringUtils.isEmpty(CameraScan.parseScanResult(data))){
                    txtsLot.setText(CameraScan.parseScanResult(data));
                }
                break;
            case REQUEST_CODE_MACHINE:
                if(!StringUtils.isEmpty(CameraScan.parseScanResult(data))){
                    txtsMachine.setText(CameraScan.parseScanResult(data));
                }
                break;
            case REQUEST_CODE_MACHINE_GROUP:
                if(!StringUtils.isEmpty(CameraScan.parseScanResult(data))){
                    txtsMachineGroup.setText(CameraScan.parseScanResult(data));
                }
                break;
            case REQUEST_CODE_PRODUCT:
                if(!StringUtils.isEmpty(CameraScan.parseScanResult(data))){
                    txtsProduct.setText(CameraScan.parseScanResult(data));
                }
                break;
        }
    }
}
